package com.xutong.myfunction.Utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xutong.myfunction.entity.Data;
import com.xutong.myfunction.entity.ResultData;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by hasee on 2016/9/26.
 */
public class HttpUtils {

    public static final String BaseURL = "http://192.168.0.106:8088";

    public static final String GetSubSystems = "/GuestApi/PrivateCloud/GetSubSystems";

    public static final String Login = "/mw-app-server/per/user/login.do";

    public static final String Community = "/MobileApi/House/GetMyCommunity";

    public static ResultData<ArrayList<Data>> get(HashMap<String,String> params){
        ResultData<ArrayList<Data>> result = null;
        HttpURLConnection httpURLConnection =null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String strParams = "";
        if (params.size()>0){
            strParams = "?"+getParams(params);
        }

        try {
            URL url = new URL(BaseURL+GetSubSystems+strParams);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");

            if (httpURLConnection.getResponseCode()==200){
                inputStream = httpURLConnection.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();
                String line = null;
                while ((line=bufferedReader.readLine())!=null ){
                    stringBuffer.append(line);
                }
                Log.d("HttpUtils-get",stringBuffer.toString());

                 result = new Gson().fromJson(stringBuffer.toString(),new TypeToken<ResultData<ArrayList<Data>>>(){}.getType());
                Log.d("HttpUtils-get","result="+result.toString());
                return result;
            }else {
                Log.d("HttpUtils-get","访问失败，错误码="+httpURLConnection.getResponseCode());
                return result;
            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (inputStream!=null){
                    inputStream.close();
                }
                if (bufferedReader!=null){
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void post(HashMap<String,String> params){

        HttpURLConnection httpURLConnection =null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        try {
            URL url = new URL(BaseURL+Login);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());

//            String conent = URLEncoder.encode("account","utf-8")+"="+URLEncoder.encode("13750000000","utf-8")
//                    +"&"+URLEncoder.encode("password","utf-8")+"="+URLEncoder.encode("123456","utf-8")
//                    +"&"+URLEncoder.encode("loginType","utf-8")+"="+URLEncoder.encode("3","utf-8")
//                    ;
            String conent = "";
            if (params.size()>0){
                conent = postParams(params);
            }

            dos.writeBytes(conent);
            dos.flush();
            dos.close();

            if (httpURLConnection.getResponseCode()==200){
                inputStream = httpURLConnection.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();
                String line = null;
                while ((line=bufferedReader.readLine())!=null ){
                    stringBuffer.append(line);
                }
                Log.e("HttpUtils-post",stringBuffer.toString());
            }else {
                Log.e("HttpUtils-post","访问失败，错误码="+httpURLConnection.getResponseCode());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (inputStream!=null){
                    inputStream.close();
                }
                if (bufferedReader!=null){
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    private static String getParams(HashMap<String,String> params){

        StringBuilder stringBuilder = new StringBuilder();
        Iterator it = params.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry entry = (Map.Entry) it.next();
            stringBuilder.append(entry.getKey()+"="+entry.getValue()+"&");
        }
        stringBuilder.deleteCharAt(stringBuilder.toString().length()-1);
//        Log.e("getParams","stringBuilder.toString()="+stringBuilder.toString());

        return stringBuilder.toString();
    }

    private static String postParams(HashMap<String,String> params){

        StringBuilder stringBuilder = new StringBuilder();
        Iterator it = params.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry entry = (Map.Entry) it.next();
            try {
                String key = URLEncoder.encode((String) entry.getKey(),"utf-8");
                String value = URLEncoder.encode((String) entry.getValue(),"utf-8");
                stringBuilder.append(key+"="+value+"&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        stringBuilder.deleteCharAt(stringBuilder.toString().length()-1);
//        Log.e("postParams","stringBuilder.toString()="+stringBuilder.toString());

        return stringBuilder.toString();
    }

    /**
     * 加载图片并返回Bitmap对象
     * @param context
     * @param imageUrl 图片url
     * @param errid 加载失败要显示的图片id
     * @return
     */
    public static Bitmap getDownload(Context context,String imageUrl,String errid){
        Bitmap bitmap = null;
        HttpURLConnection httpURLConnection =null;
        InputStream inputStream = null;

        try {
            URL url = new URL(imageUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");

            if (httpURLConnection.getResponseCode()==200){
                inputStream = httpURLConnection.getInputStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            }else {
                Log.d("HttpUtils-get","访问失败，错误码="+httpURLConnection.getResponseCode());
                bitmap = BitmapFactory.decodeResource(context.getResources(),Integer.parseInt(errid));
                return bitmap;
            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }


}
